package cn.itcast.emp;

import cn.itcast.utils.JDBCutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 版权：卓灿教育集团 版权所有
 * author :赵航
 *
 * @e-mail: zhaohangcn@gmail.com
 * time：2021/2/16
 * describe ：
 */
public class Count {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement1 = null;
        PreparedStatement preparedStatement2 = null;
        try {
            connection = JDBCutils.getConnection();
            String sql1 = "update account set salary = salary - ? where id = ?";
            String sql2 = "update account set salary = salary + ? where id = ?";

            //开启事务
            connection.setAutoCommit(false);

            preparedStatement1 = connection.prepareStatement(sql1);
            preparedStatement2 = connection.prepareStatement(sql2);

            preparedStatement1.setDouble(1, 500);
            preparedStatement1.setInt(2, 1);

            preparedStatement2.setDouble(1, 500);
            preparedStatement2.setInt(2, 2);

            preparedStatement1.executeUpdate();
            preparedStatement2.executeUpdate();

            connection.commit();

        } catch (Exception e) {
            //事务的回滚
            try {
                if (connection != null)
                    connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JDBCutils.colse(preparedStatement1, connection);
            JDBCutils.colse(preparedStatement2, null);
        }
    }
}
